package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTRecycle_operation_dsstaff
 * @Description:华盛证券 回收
 * @author: xrm
 * @date 2022-12-20 15:52:00
 *
 */

public class aipHSTRecycle_operation_dsstaff implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTRecycle_operation_dsstaff.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData );
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
			log.debug("dayin");
			JSONObject inObject = new JSONObject(inData);
			log.debug("原始inObject inObject:" + inObject);

			def edit_rolegroupid = inObject.getString("edit_rolegroupid");//新组id
			def edit_staffid = inObject.getString("edit_staffid");//staffid
			def edit_rolegrouptype = inObject.getString("edit_rolegrouptype");//操作类型
			def defaultrolegroup = inObject.getString("defaultrolegroup");//原组id
			def defaulstaffid = inObject.getString("defaulstaffid");//操作人id
			
            log.debug("新组id:" + edit_rolegroupid +" | staffid:"+ edit_staffid + " | 操作类型:"+ edit_rolegrouptype);
			
			if(edit_rolegrouptype=="0"){
				String[] custTaskDealSQL = new String[4];
				//回收objective表数据
			    custTaskDealSQL[0] = "update objective set HANDLEGROUP_ID = '"+edit_rolegroupid+"' where HANDLEBY_ID= '"+edit_staffid+"' and MAP_ID='MY48ZX'";
				//回收elitetask表数据
				custTaskDealSQL[1] = "update elitetask set HANDLEGROUP_ID = '"+edit_rolegroupid+"' where HANDLEBY_ID= '"+edit_staffid+"' and MAP_ID='MY48ZX'";
				//新增assign_his记录表
				custTaskDealSQL[2] = "insert into staff_group_update_his(lod_HANDLEGROUP_ID,new_HANDLEGROUP_ID,CREATEDDATE,CREATEDBY,staff_id)values ('"+defaultrolegroup+"', '"+edit_rolegroupid+"' ,NOW(),'"+defaulstaffid+"','"+edit_staffid+"')"
				//修改staff记录表hs_json
				custTaskDealSQL[3] = "update staff set hs_json='' where staff_id= '"+edit_staffid+"'";
				
				int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
				log.debug("SQL返回结果："+batchSQLResult.toString());
				
			}
			
			if(edit_rolegrouptype=="1"){
		    
			//创建一个批次号
			long time=new Date().getTime();
			System.out.println(""+time);
			Date dates=new Date(time);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
			String times=sdf.format(dates);

			String advisory_batchid = "回收批次" + times; //批次号
			//根据staffid查出objective表里符合条件的数据
            List objectivelist = eliteBean.chaxun_sql("SELECT e.OBJECTIVE_GUID as OBJECTIVE_GUID,e.CUSTOMER_GUID as CUSTOMER_GUID,o.CREATEDDATE as CREATEDDATE,o.HANDLEGROUP_ID as HANDLEGROUP_ID,o.HANDLEBY_ID as HANDLEBY_ID,c.CUSTOMER_ID as CUSTOMER_ID FROM objective o left join elitetask e on o.OBJECTIVE_GUID=e.OBJECTIVE_GUID left join customer c on o.customer_guid=c.customer_guid where o.HANDLEBY_ID='"+edit_staffid+"' and o.MAP_ID='MY48ZX' AND (O.cancellationstatus IS NULL or O.cancellationstatus ='')", "dataSource");
	
			if(objectivelist.size()>0) {//循环遍历			
				int arrInt = objectivelist.size();
				log.debug(arrInt);
	            for (int i = 0; i < arrInt; i++) {
					//华盛接口连续调用可能异常 添加1S睡眠
					Thread.sleep(1 * 1000);
					
					String OBJECTIVE_GUID = objectivelist.get(i).get("OBJECTIVE_GUID");	
					log.debug(OBJECTIVE_GUID);
					String CUSTOMER_GUID = objectivelist.get(i).get("CUSTOMER_GUID");
					log.debug(CUSTOMER_GUID);
                    String CREATEDDATE = objectivelist.get(i).get("CREATEDDATE");//上次分配时间		
                    log.debug(CREATEDDATE);					
					String oldhandlegroup_id = objectivelist.get(i).get("HANDLEGROUP_ID");//assign_his上次处理组ID
					log.debug(oldhandlegroup_id);
					String oldhandleby_id = objectivelist.get(i).get("HANDLEBY_ID");//assign_his上次处理人ID
					log.debug(oldhandleby_id);
					String customer_id = objectivelist.get(i).get("CUSTOMER_ID");//华盛号
                    log.debug(customer_id);
					
					//调用解绑接口
                    String injson="{\"hsNo\""+":"+"\""+customer_id+"\",\"divideType\":2}"
                    String doURL ="";
                    String sysurl = getProperty.get("crmurl");//配置本地接口地址
                    doURL = sysurl+"aipHSTBindCounselor";
                    log.debug("doURL:" + doURL);
                    Map<String, String> headMap = new HashMap<String, String>();
                    headMap.put("Content-Type", "application/x-www-form-urlencoded");
                    def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
                    log.debug("getResult:" + getResult);
					
					JSONObject jsonObject = new JSONObject(getResult);
					String code = GetJV(jsonObject, "result");
					log.debug("绑定接口返回code：" + code);
					//api接口 成功 则分配
					if (code == "1") {
						String[] custTaskDealSQL = new String[3];
						//回收objective表数据
						custTaskDealSQL[0] = "update objective set HANDLEGROUP_ID='' ,HANDLEBY_ID='',recycledate=now(),CUSTLISTNAME='" + advisory_batchid + "',objectivesubstatus='' where OBJECTIVE_GUID='"+OBJECTIVE_GUID+"'";
						//回收elitetask表数据
						custTaskDealSQL[1] = "update elitetask set HANDLEGROUP_ID='' ,HANDLEBY_ID='',objectivesubstatus='',MODIFIEDDATE=null where OBJECTIVE_GUID='"+OBJECTIVE_GUID+"'";
						//新增assign_his记录表
						custTaskDealSQL[2] = "insert into assign_his(assign_guid,customer_guid,objective_guid,oldhandlegroup_id,oldhandleby_id,newhandlegroup_id,newhandleby_id,success_guid,lastassigndate,advisory_batchid,ASSIGNGROUP_ID,ASSIGNBY_ID,ASSIGNDATE,RETURNGROUP_ID,RETURNBY_ID,RETURNDATE) VALUES (UUID(),'"+CUSTOMER_GUID+"','"+OBJECTIVE_GUID+"','"+oldhandlegroup_id+"','"+oldhandleby_id+"',null,null,'账号管理回收数据','"+CREATEDDATE+"','"+advisory_batchid+"','SYSTEM','SELITE',NOW(),'SYSTEM','SELITE',NOW())"
						
						int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
						log.debug("SQL返回结果："+batchSQLResult.toString());
					//涉及绑定接口 调度 存在注销客户的情况
					}else if (code == "10013") {
						String updateObjSQL = "update objective set cancellationstatus='注销' where OBJECTIVE_GUID='"+OBJECTIVE_GUID+"'";
						def updateObjSQLresult= eliteBean.update(updateObjSQL, "dataSource");
						log.debug("客户已注销！标识更新："+updateObjSQLresult);
					}else{
						log.debug("解绑接口失败！");
					}
	
			    }

					//获取当前顾问待回收任务数量
					List objtasklist = eliteBean.chaxun_sql("select count(*) as objtask_number from  objective where  HANDLEBY_ID='"+edit_staffid+"' and MAP_ID='MY48ZX' and cancellationstatus is null", "dataSource");
					def objtask_number = objtasklist.get(0).get("objtask_number");
					log.debug("objtask_number"+objtask_number);

					//获取数据回收总量
					List recovery_numberlist = eliteBean.chaxun_sql("select count(*) as recovery_number from assign_his where advisory_batchid = '"+advisory_batchid+"'", "dataSource");
					def recovery_number = recovery_numberlist.get(0).get("recovery_number");
					log.debug("recovery_number"+recovery_number);

					//获取数据回收总量
					List recovery_namelist = eliteBean.chaxun_sql("select staffname from staff where staff_id = '"+edit_staffid+"'", "dataSource");
					def recovery_name = recovery_namelist.get(0).get("staffname");
					log.debug("recovery_name"+recovery_name);

					if(recovery_number>0){
						String INSERThst_recycle_checkSQL = "INSERT INTO hst_recycle_check(recycle_check_guid, recovery_guid, recovery_type, recovery_number, recovery_date ,advisory_batchid,recovery_name) VALUES (uuid(),null , '离职|换岗回收', '"+recovery_number+"', now(),'"+advisory_batchid+"','"+recovery_name+"')";
						def INSERThst_recycle_checkSQLresult= eliteBean.update(INSERThst_recycle_checkSQL, "dataSource");
						log.debug("写入批次轨迹表更新："+INSERThst_recycle_checkSQLresult);
					}else{
						log.debug(edit_staffid+" 回收0条数据！");
					}

					//修改staff记录表hs_json
					if(objtask_number==0){//判断 当前回收顾问是否还有
						String updatestaffSQL = "update staff set hs_json='' where staff_id= '"+edit_staffid+"'";
						def updatestaffSQLresult= eliteBean.update(updatestaffSQL, "dataSource");
						log.debug("更新staff的任务json参数："+updatestaffSQLresult);
					}else{
						log.debug(edit_staffid+" 回收未完成！剩余:"+objtask_number);
					}

			}else{//账户回收 数据0 则清空json
				String updatestaffSQL = "update staff set hs_json='' where staff_id= '"+edit_staffid+"'";
				def updatestaffSQLresult= eliteBean.update(updatestaffSQL, "dataSource");
				log.debug("更新staff的任务json参数："+updatestaffSQLresult);
			}
				//执行情况 1 在执行 null为待执行
				String updatestaffSQL1 = "update staff set hs_type=null where staff_id= '"+edit_staffid+"'";
				def updatestaffSQLresult1= eliteBean.update(updatestaffSQL1, "dataSource");
				log.debug("更新staff的任务type参数："+updatestaffSQLresult1);
				
			}

            outData = "{\"result\":\"1\",\"message\":\"回收成功\",\"data\":[]}";


        } catch (Exception e) {
            //log.error("接口处理异常" + e.getMessage());
			log.error("接口处理异常" + e.getMessage(),e);
			// 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"回收失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    // 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;

		try {
			Rev_Value = String.valueOf(inJson.getBoolean(getKey));
		} catch (Exception e6) {
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e5) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e4) {
					try {
						Rev_Value = String.valueOf(inJson.getLong(getKey));
					} catch (Exception e11) {
						try {
							Rev_Value = String.valueOf(inJson.getDouble(getKey));
						} catch (Exception e1) {
							try {
								Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
							} catch (Exception e2) {
								try {
									Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
								} catch (Exception e3) {
									Rev_Value = "";
								}
							}
						}
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
